
<!-- ************************************************************************************************
* ***************************************双队比赛制文件***********************************************
************************************************************************************************ -->

<template>
	<div class="">
		<bread-crumb>創建賽事-足球</bread-crumb>
		<div class="uc-body">
			<!--工具栏-->
			<!--<div class="manage-top"><span>左</span><span>右</span></div>-->
			<vote-create-topbar></vote-create-topbar>
			<!--***********************************************填写表单***********************************************-->
			<div class="manage-form">
                <!---->
				<div class="item">
					<div class="label">賽事名稱</div>
					<div class="con">
						<el-input class="w150" size="small" v-model="submitObject.game_info_idp" clearable placeholder="請輸入賽事名稱" ></el-input>
					</div>
				</div>
				<!---->
				<div class="item">
					<div class="label">參賽主隊</div>
					<div class="con">
						<el-input class="w100" size="small" v-model="submitObject.contest_master" clearable></el-input>
					</div>
				</div>
				<!---->
				<div class="item">
					<div class="label">參賽客隊</div>
					<div class="con">
						<el-input class="w100" size="small" v-model="submitObject.contest_branch" clearable></el-input>

					</div>
				</div>

				<div class="item">
					<div class="label">競技類型</div>
					<div class="con">
						<el-select class="w150" size="small" @change="actOnGameChange" v-model="submitObject.gameTag"  placeholder="請選擇類型">
							<el-option
								v-for="(item,index) in competitionSportsType" :key="item.gameTag" :label="item.title" :value="item.gameTag">
							</el-option>
						</el-select>
					</div>
				</div>

				<!---->
				<div class="item">
					<div class="label">玩法規則</div>
					<div class="con">
						<el-select class="w150" size="small" @change="actOnPlayTypeChange" v-model="submitObject.playTag" placeholder="請選擇玩法">
							<el-option
								v-for="(item,index) in competitionPlayType" :key="item.playTag" :label="item.playTitle" :value="item.playTag">
							</el-option>
						</el-select>
					</div>
				</div>
				<!---->

				<div class="item">
					<div class="label">玩法賠率</div>
					<div class="con">
						<div>
							<div class="el-input--small mt5" v-for="item in computeOddsFormat">
								<!--狗日的遍歷的el-input不能輸入！？-->
								<!--<el-input ref="odds-input" class="w100" type="number" size="small" @input="onInput()"></el-input>-->
								<input class="el-input__inner w100"  type="number" ref="odds-input" placeholder="請輸入">
								{{item}}
							</div>
						</div>
					</div>
				</div>
				<div class="item">
					<div class="label">最低賠率</div>
					<div class="con">
						<el-input class="w100" type="number" size="small" v-model="submitObject.lowest_oddsp"></el-input>
						<el-popover placement="top-end" title="提示" width="200" trigger="click" content="此參數用於保證玩家的獎勵，建議不低於1">
							<i class="f24 el-icon-question" slot="reference"></i>
						</el-popover>
					</div>
				</div>

                <!---->
				<div class="item">
					<div class="label">投票截止</div>
					<div class="con"><el-date-picker v-model="submitObject.vote_end_timep" type="datetime" size="small" value-format="timestamp" placeholder="選擇日期時間"></el-date-picker></div>
				</div>
				<div class="item">
					<div class="label">投注開始</div>
					<div class="con"><el-date-picker v-model="submitObject.bet_start_timep" type="datetime" size="small" value-format="timestamp" placeholder="選擇日期時間"></el-date-picker></div>
				</div>
				<div class="item">
					<div class="label">投注截止</div>
					<div class="con"><el-date-picker v-model="submitObject.bet_end_timep" type="datetime" size="small" value-format="timestamp" placeholder="選擇日期時間"></el-date-picker></div>
				</div>
				<div class="item">
					<div class="label">開賽時間</div>
					<div class="con"><el-date-picker v-model="submitObject.contest_start_timep" type="datetime" size="small" value-format="timestamp" placeholder="選擇日期時間"></el-date-picker></div>
				</div>
				<!---->
				<create-vote-money
					:submitObject="submitObject"
					:betCoinData="betCoinData"
					:betCoinSupport="betCoinSupport"
					:betCoinSelected="betCoinSelected"
					:betCoinInput.sync="betCoinInput"
					:lockUpAmount="lockUpAmount"
					@actSelectCoin="actSelectCoin"
					@actGetCustomTokenInfo="actGetCustomTokenInfo"
				>

				</create-vote-money>
				<!--下面这个已经抽离为组件，测试没问题后删掉-->
				<!--<div class="item">
					<div class="label">投注幣種</div>
					<div class="con">
						&lt;!&ndash;自定义读取&ndash;&gt;
						<div style="width:100%;">
							<div class="c-red" v-if="dev">测试网只能用提供的自定支持币种</div>
							<div>
								<el-button
									size="small"
									v-for="item in betCoinSupport"
									:key="item.symbol"
									:type="item.symbol==betCoinSelected?'primary':'info'"
									@click="actSelectCoin(item.symbol)"
									round
								>
									{{item.name}}
								</el-button>
							</div>
							<div v-show="betCoinSelected=='CUSTOM'">
								<el-input
									type="textarea" class="mt5"
									:autosize="{ minRows: 2, maxRows: 4}"
									placeholder="請輸入幣合約地址，并點擊下方讀取按鈕"
									v-model="betCoinInput"
									clearable
								>
								</el-input>
								<div class="mt5">
									<el-button size="small" type="success" round @click="actGetCustomTokenInfo()">讀取幣種信息</el-button>
								</div>
								<div v-if="betCoinData.decimal > 0">
									<div>幣種名稱：{{betCoinData.symbol}}</div>
									<div>幣種精度：{{betCoinData.decimal}}</div>
								</div>
								&lt;!&ndash;<div class="c-red" v-else>幣種無效，請先讀取</div>&ndash;&gt;
							</div>
						</div>
					</div>
				</div>

				<div class="item">
					<div class="label">投注範圍</div>
					<div class="con">
						<el-input class="w100" size="small" v-model="submitObject.bet_min_amount" placeholder="最小" type="number" clearable></el-input>
						~
						<el-input class="w100" size="small" v-model="submitObject.bet_max_amount" placeholder="最大" type="number" clearable></el-input>
					</div>

				</div>
				<div class="item">
					<div class="label">獎池注入</div>
					<div class="con">
						<el-input class="w80" size="small" v-model="submitObject.totalBetL" disabled>USDT</el-input>
						&lt;!&ndash;<span class="c-red">輸入時即時計算</span>&ndash;&gt;
						<span v-if="betCoinData.decimal > 0">{{betCoinData.symbol}}</span>
						<el-popover placement="top-end" title="提示" width="200" trigger="click" content="賽事獎池，需要打入的投注幣數量（目前的算法：所有賠率總和*最大投注）">
							<i class="f24 el-icon-question" slot="reference"></i>
						</el-popover>
						&lt;!&ndash;<el-button type="success" size="small" @click="funcComputeJackpot()">預覽計算</el-button>&ndash;&gt;
					</div>
				</div>
				<div class="item">
					<div class="label">質押票數</div>
					<div class="con">
						{{lockUpAmount + xg.name}}
						<el-popover placement="top-end" title="提示" width="200" trigger="click" content="需要質押的代幣數量。投票失敗、作廢、投票成功賽事開獎後，方可取回">
							<i class="f24 el-icon-question" slot="reference"></i>
						</el-popover>
					</div>
				</div>-->
				<!---->
				<div class="flex-jc-c mt10 p10">
					<el-button class="w-100" type="primary" @click="submitValidate" :loading="submiting" :disabled="submiting" round>發布赛事</el-button>
				</div>
				<div class="block"></div>
			</div>

			<!--***********************************************表单结束***********************************************-->
			<!--***********************************************表单结束***********************************************-->
			<!--***********************************************表单结束***********************************************-->
		</div>
	</div>
</template>

<script>

//基础资源
import breadCrumb from '../components/breadCrumb.vue'
import voteCreateTopbar from "./components/voteCreateTopbar";
import createVoteMoney from "./components/createVoteMoney";
import { mixins } from '@/mixins/mixins'
import { mixinsUtils } from '@/mixins/mixins.utils'
import { mixinsManage } from "@/views/manage/js/manage.mixins";
import { tronCreateVote, apiVotingAnalysisServe, } from "./js/manage.user.lib";
import { encodeParams, smartContractBroadcastCallback, smartContractConfirmCallback, } from "@/libs/site.utils";
import { validateScore } from "../../manage/js/manage.func";
import { mixinsVoteCreate } from "./js/mixins.vote.create";
import { GAME_TYPE, GAMES_OBJECT } from "@/views/contestHall/contest.lib";


/////////////////////////////////////////////////////////数据处理///////////////////////////////////////////////////////////
//游戏数据
const GAMES_DATA = [
	...GAMES_OBJECT[GAME_TYPE.FOOTBALL],
]
const teams = ['老鹰', '凯尔特人', '公牛', '黄蜂', '骑士', '热队', '尼克斯', '活塞', '魔术', '76人', '猛龙', '奇才', '步行者', '独行侠', '掘金', '勇士', '快船', '森林狼', '火箭', '灰雄', '湖人', '太阳', '开拓者', '国王', '爵士', '马刺', '灰雄']

////////////////////////////////////////////////////////导出///////////////////////////////////////////////////////////
export default {
	name:"manageCreateVoteFootball",
	components: { breadCrumb,voteCreateTopbar,createVoteMoney },
	mixins:[mixins,mixinsUtils,mixinsManage,mixinsVoteCreate],
	//用于开发的
	data () {
		return {
			/*************************************简单值***********************************/

			/*************************************复杂值***********************************/
			//体育类型(每个页面数据不同，这里不能弄到mixins)
			competitionSportsType:Object.freeze(GAMES_DATA),
			//玩法
			competitionPlayType:[],
			//选中的玩法的规则，不一定有使用?
			competitionPlayRule:{},
			//要提交的数据
			submitObject :{
				//只保存到服务器的
				gameTag : "",//体育类型标识
				groupType: "",//分组类型，比如两队，无队，或多队，保存到数据库，不一定用得上
				playTitle: "",// 玩法名称，存后台
				playTag  : "", //玩法标识符，存后台
				//区块链要用的数据
				playType           : "",// 玩法，要存区块链中？？
				bet_max_amount     : "",
				bet_min_amount     : "",
				game_info_idp      : "NBA2021",//赛事名称
				default_oddsp      : [1, 1, 1], //玩法的默认赔率 //todo 这个要整改
				lowest_oddsp       : '1',//最低p率
				totalBetL          : '0',//基础池

				// ruleId             : '1',//玩法，应该是一个标识 //这个已经没用了，现在一个合约只存一个玩法算法
				vote_end_timep     : Date.parse(new Date()) + (60 * 1 * 2) * 1000,//投票截止时间
				bet_start_timep    : Date.parse(new Date()) + (60 * 1 * 3) * 1000,//GG投注开始时间
				bet_end_timep      : Date.parse(new Date()) + (60 * 1 * 6) * 1000,//投注结束时间
				contest_start_timep: Date.parse(new Date()) + (60 * 60 * 100) * 1000,//开塞时间
				contest_master     : teams[Math.floor(Math.random() * teams.length)],//主队
				contest_branch     : teams[Math.floor(Math.random() * teams.length)],//客队
			},
		}
	},
	computed: {
        //提取odds格式，用于遍历显示
        computeOddsFormat(){
	        return ['胜','平','负']
        }
	},
	created () {
		this.actOnGameChange(GAME_TYPE.FOOTBALL) //默认选择游戏
	},
	mounted () {
    },
	methods: {
		//提交验证（不抽离，因为每个类型的表单不一样）
		submitValidate(){
			let _sbumitdata   = this.submitObject
			let _oddsArray    = [] //P率数据
			let _validateOdds = true //默认验证成功

			//是否有填寫賽事名稱
			if(_sbumitdata.game_info_idp.trim() == ''){
				this.$notify({title:'錯誤',type:'error',message:'塞事名稱沒有填寫！'})
				return false
			}

			//隊伍名稱
			if(_sbumitdata.contest_master.trim() == '' || _sbumitdata.contest_branch.trim()==''){
				this.$notify({title:'錯誤',type:'error',message:'參賽者名稱沒有填寫！'})
				return false
			}

			//odds處理
			if(this.$refs['odds-input'] == undefined){
				this.$notify({title:'錯誤',type:'error',message:'請選擇玩法類型！'})
				return false
			}else {
				this.$refs['odds-input'].forEach((item) => {
					let _value = item.value //取到value
					if (!validateScore(_value, ['less', 'zero'], '賠率錯誤，不可為0或小於1')) {
						_validateOdds = false //只有要一個不合格，驗證就失敗
					} else {
						_oddsArray.push(_value)
					}
				})
				if (_validateOdds) { //odds填寫驗證通過
					this.submitObject.default_oddsp = [..._oddsArray] //賦值到提交對象
					console.log('odds驗證通過：', _oddsArray)
				} else {
					return false
				}
			}


			//验证各阶段时间前后顺序，以防输入错误
			let { vote_end_timep,bet_start_timep,bet_end_timep } = this.submitObject
			if(vote_end_timep=='' || bet_start_timep=='' || bet_end_timep==''){
				this.$notify({title:'錯誤',type:'error',message:'相關時間必須填寫'})
				return false
			}
			if(!(vote_end_timep < bet_start_timep && bet_start_timep < bet_end_timep)){
				this.$notify({title:'錯誤',type:'error',message:'時間先後順序有誤'})
				return false
			}

			//檢測幣種是否有效
			if (this.betCoinData.decimal == 0) {
				this.$notify({title:'錯誤',type:'error',message:'沒有填寫投注幣種或無效！請檢查'})
				return false
			}

			//檢驗投注範圍與有效值
			let _bet_max_amount = parseInt(this.submitObject.bet_max_amount)
			let _bet_min_amount = parseInt(this.submitObject.bet_min_amount)
			console.log('>>>>>>>>>>>>>>>投注範圍：',_bet_min_amount,_bet_max_amount)
			if (_bet_max_amount <= _bet_min_amount) {
				this.$notify.error('投注範圍不正確!')
				return
			}
			if(_bet_min_amount<1 || _bet_max_amount < 1 || isNaN(_bet_min_amount) || isNaN(_bet_max_amount)){
				this.$notify.error('投注范围不能小於1!')
				return
			}

			//下一步
			this.$notify({title:'提示',type:'success',message:'填寫內容通過驗證，進入下一步！'})
			this.funcComputeJackpot()//数据验证通过，就计算一下奖池？？
			this.createProposal() //下一步
		},

		//提交前数据处理 (这个不抽离，提交的数据都不同)
		createProposalImpl(sender) {
			//处理默认P率
			let that = this;
			let default_odds = this.submitObject.default_oddsp.map(item => item * this.rateAmplify)
			//获取币种精度
			let bet_decimal = that.betCoinData.decimal;
			let _submitdata = that.submitObject;
			//时间取整数，避免小数运算
			let start_of_betting = parseInt(_submitdata.bet_start_timep / 1000);
			let end_of_betting   = parseInt(_submitdata.bet_end_timep / 1000);
			let vote_end_timep   = parseInt(_submitdata.vote_end_timep / 1000);
			let game_start       = parseInt(_submitdata.contest_start_timep / 1000);
			let bet_max_amount_  = parseInt(_submitdata.bet_max_amount * Math.pow(10, bet_decimal));
			let bet_min_amount_  = parseInt(_submitdata.bet_min_amount * Math.pow(10, bet_decimal));

			//组织、处理参数
			const parameter = [
				{type: 'string', value: _submitdata.game_info_idp.trim() + "|" + _submitdata.contest_master.trim() + "|" + _submitdata.contest_branch.trim()},
				//玩法类型(没用了，新版一个合约只存在一个玩法算法)
				// {type: 'uint256', value: _submitdata.ruleId},
				//[投注开始时间，投注结束时间，投注最大金额，投注最小金额]
				{
					type: 'uint256[]',
					value: [start_of_betting, end_of_betting, bet_max_amount_, bet_min_amount_]
				},
				//投注币种
				{type: 'address', value: tronWeb.address.toHex(that.betCoinData.address.trim())},
				//赛事玩法赔率
				{type: 'uint256[]', value: default_odds},
				//最低赔率
				{type: 'uint256', value: _submitdata.lowest_oddsp * that.rateAmplify},
				//比赛开赛时间
				{type: 'uint256', value: game_start},
				//打入的初始金额
				{type: 'uint256', value: parseInt(_submitdata.totalBetL * Math.pow(10, bet_decimal))},
			]
			console.log(parameter)
			let param = encodeParams(parameter);

			//执行投票。传递参数。参数转换bytes
			let addParameters = "0x" + param;
			const ACTION_TITLE = `${_submitdata.game_info_idp} ${_submitdata.contest_master}vs${_submitdata.contest_branch}`
			const ACTION = that.LangSet(['發起投票賽事:', 'createVote:'])
			tronCreateVote(
				this.sender,
				vote_end_timep,
				footContract,
				addParameters,
				smartContractBroadcastCallback(ACTION, ACTION_TITLE, (status, txid) => {
					that.submiting = false //恢复可提交
					console.log('hash:', txid)
					if (status == 1) {
						apiVotingAnalysisServe({}, txid); //通知服务器根据hash爬新数据
						setTimeout(() => {
							//如果这里刷新 ，则会有tronweb对象加载顺序的问题，导致显示或数据不显示?
							window.location.reload()
						}, 2000)
					}
				}),
				smartContractConfirmCallback(ACTION, ACTION_TITLE)
			);
		},


        /////////////////////////////////////////////////  其它交互处理 /////////////////////////////////////////////
        /////////////////////////////////////////////////  其它交互处理 /////////////////////////////////////////////
        /////////////////////////////////////////////////  其它交互处理 /////////////////////////////////////////////


		//todo 这个看怎么抽离？ 里面结合了p率计算，有的竞技不需要这个数据来参与计算？？
		//输入tz范围值时，计算奖池
		funcComputeJackpot(){
			console.log('计算需要打入奖池的数量...')
			let _bet_max_amount = parseInt(this.submitObject.bet_max_amount);
			let _bet_min_amount = parseInt(this.submitObject.bet_min_amount);
			if (_bet_max_amount <= _bet_min_amount) {
				// this.$message.error('投注范围不正确!');
				return;
			}
			if(_bet_min_amount<1 || _bet_max_amount < 1 || isNaN(_bet_min_amount) || isNaN(_bet_max_amount)){
				// this.$message.error('投注值不能小于1!');
				return;
			}
			//只有输入正确才计算需要注入的奖池
			let _oddsArray = []
			let _oddsSum  = 0
			let _validate = true //默认验证成功
			//是否已经动态渲染出表单
			if(this.$refs['odds-input'] != undefined){
				this.$refs['odds-input'].forEach((item) => {
					// let _value = item.value //取到value
					if (!validateScore(item.value, ['less', 'zero'], '赔率不可为0或小于1')) {
						_validate = false
					} else {
						_oddsArray.push(item.value)
					}
				})
				_oddsSum = _oddsArray.reduce((ret,prev)=>{
					return ret+= parseFloat(prev)
				},0)
			}

			//验证通过，才计算，注意，提交前还会再计算一次，这里只用来显示，以防计算好后，又改了范围
			if(_validate == true){
				this.submitObject.totalBetL = parseFloat(this.submitObject.bet_max_amount) * parseFloat(_oddsSum);
			}

		},

	},
	/*********************************************************  方法结束 **********************************************/
	watch:{

	},
	beforeDestroy() {
		//销毁延迟任务
		window.clearTimeout(this.contractInfoTime);
	},
}
</script>

<style lang="less" scoped>
/*公共变量*/
@import '~@/assets/global.less';

/************************************适应***************************************/
@media screen and (max-width: @MINSCREEN){

}
</style>
